package com.company.huisuo.repository

import com.company.huisuo.biz.bean.LoginData
import com.company.huisuo.biz.bean.LoginRequest
import com.company.huisuo.biz.bean.LoginResponse
import com.company.huisuo.network.RetrofitClient
import com.company.huisuo.network.api.AuthApi
import com.company.huisuo.network.auth.TokenManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 认证数据仓库
 */
class AuthRepository {
    
    private val authApi: AuthApi by lazy {
        RetrofitClient.createService()
    }
    
    /**
     * 设备登录
     */
    suspend fun deviceLogin(deviceAccount: String = "test2", password: String = "123456"): Result<LoginData> = withContext(Dispatchers.IO) {
        try {
            val loginRequest = LoginRequest(deviceAccount, password)
            val response = authApi.deviceLogin(loginRequest)
            if (response.code == 0 && response.data != null) {
                // 登录成功，保存token
                val loginData = response.data
                TokenManager.saveToken(
                    loginData.userId,
                    loginData.accessToken,
                    loginData.refreshToken,
                    loginData.expiresTime
                )
                Result.success(loginData)
            } else {
                Result.failure(Exception(response.message ?: "登录失败"))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
    
    /**
     * 检查是否已登录
     */
    fun isLoggedIn(): Boolean {
        return TokenManager.isTokenValid()
    }
    
    /**
     * 退出登录
     */
    fun logout() {
        TokenManager.clearTokens()
    }
    
    /**
     * 刷新token
     */
    suspend fun refreshToken(): Result<Boolean> = withContext(Dispatchers.IO) {
        try {
            // 这里可以添加刷新token的API调用
            // 暂时返回成功，实际项目中需要调用刷新token的API
            Result.success(true)
        } catch (e: Exception) {
            Result.failure(Exception("刷新token失败: ${e.message}"))
        }
    }
}